<?php

/**
 * This file is accessed through JavaScript and executes code on the server side (AJAX).
 * Loads modules (leftmenu, admin menu, centerarea)
 * 
 * @author Siim Loog
 */

session_start();
require_once 'init.php';

if(empty($_SESSION)){
	echo "LoggedOut";
	exit;
} 


if ( !isset($_POST['action']) ) {
	if ( !isset($_GET['action']) ) {
		exit;
	} else {
		switch( $_GET['action'] ) {
			
			//load result for grading and giving feedback
			case 'loadResult':
				
				if(!isset($_SESSION['oppejoud'])){
					exit;
				}
				$resultId = $_GET['resultId'];
				
				$result = Result::loadResult($sql, $resultId);
				if(!$result){
					echo "Soorituses pole lahendusi";
				} else {
					echo '<br/>';
					echo '<button onclick="gradeResult('.$result[0]['sooritus'].');" class="answerButton">Hinda</button>';
					echo '<br/>';
					echo '<br/>';
					foreach ($result as $value) {
						$identifier = "entity".strval($value['idlahendus']);
						$points = "points".strval($value['idlahendus']);
						echo '<div class="answer">
							<div class="problemDescription">
							<p><b>Ülesanne: </b>';
						echo ''.$value['tekst'].'';
						echo '<br/>
							</p><p>
							<b>Õige vastus 1: </b>';
						echo ''.html_entity_decode($value['vastus']).'';
						echo '<br/>
							</p><p>
							<b>Õige vastus 2:</b> ';
						echo ''.html_entity_decode($value['vastus2']).'';
						echo '<br/>
							</p><p>
							<b>Õige vastus 3: </b>';
						echo ''.html_entity_decode($value['vastus3']).'';
						echo '<br/>
							</p><p>		
							<b>Õpilase vastus:</b> ';
						echo ''.html_entity_decode($value['pakkumine']).'';
						echo '<br/>
							<div class="studentGuess"><p>
								<b>Sisesta tagasiside:</b> <br />
								<textarea rows="3"  cols="50" oninput="resetFeedBackStatus('.$value['idlahendus'].');"  name="';
						echo ''.$identifier.'';
						echo '" id = "';
						echo ''.$identifier.'';
						echo '">';
						echo ''.html_entity_decode($value['tagasiside']).'</textarea>
							</div>
							<div class="buttonPad">
							</div>
							</p><p>
								<b>Punkte:</b><br />
								<input type="number" min="1" max="'.$value['maks_punkte'].'" step="1"  oninput="resetFeedBackStatus('.$value['idlahendus'].');" value="';
						if($value['punktid']>0){
							echo $value['punktid'];
						} else echo "0";
						echo '" name="'.$points.'" id="'.$points.'" /><br/>
							</p><p>
								<button onclick="setFeedback('.$value['idlahendus'].');" class="answerButton">Kinnita</button>
								<div class="answerStatus" id="answerStatus'.$value['idlahendus'].'">';
						
						if($value['tagasiside'] || $value['punktid']){
							echo "Tagasiside salvestatud";	
						}
						echo 	'</div></p>';
						echo '</div></div>';
					}
					echo '<br/>';
					echo '<br/>';
					echo '<button onclick="gradeResult('.$result[0]['sooritus'].');" class="answerButton" style="clear:both;">Hinda</button>';
					
					
				}
				break;
				
				
				
			//load result for grading and giving feedback
			case 'viewResult':
				$resultId = $_GET['resultId'];
				
				$result = Result::loadResult($sql, $resultId);
				if(!$result){
					echo "Soorituses pole lahendusi";
				} else {
					
					foreach ($result as $value) {
						$identifier = "entity".strval($value['idulesanne']);
						echo '<div class="answer">
							<div class="problemDescription">
							<p><b>Ülesanne:</b> ';
						echo ''.$value['tekst'].'';
						echo '<br/>
							</p><p>		
							<b>Minu vastus: </b>';
						echo ''.html_entity_decode($value['pakkumine']).'';
						echo '<br/>
							<b>Tagasiside:</b><br />';
					
						echo ''.html_entity_decode($value['tagasiside']).'
							<div class="buttonPad">
							</div>
							</p><p>
								<b>Punkte:</b><br />';
						if($value['punktid']>0){
							echo $value['punktid'];
						} else echo "0";
						
						echo '/'.$value['maks_punkte'].'
								<br/>
							</p>';
						echo '</div></div>';
					}
				}
				break;
				
				
			}
	}
} else {

		switch( $_POST['action'] ) {
			// create an answer and tie it to the solution
			// also checks if the guess matches any of the correct answers defined by the teacher
			// return the inserted answer and the initial decision if the answer is correct
			case 'insertAnswer':
				$vastus = htmlentities($_POST['vastus']);
				$sooritus = $_SESSION['sooritus'];
				$ulesanne = $_POST['ulesanneId'];
				$kontrolltoo = $_SESSION['testId'];
				$result = Solution::insert($sql, $sooritus, $vastus, $ulesanne, $kontrolltoo);
				
				
				$feedback['answer'] = "";
				$feedback['decision'] = "";
				$feedback['testStatus'] = "";
				
				if($result == "Töö suletud"){
						$feedback['testStatus'] = "Closed";
						echo json_encode($feedback);
						break;
						
				}
				

				
				$feedback['answer'] = html_entity_decode($result);
				
				$guess = $vastus;
				$questionId = $ulesanne;
				$problem = Problem::problemAnswer($sql, $questionId);
				
				// correct answers and the decision about them. 
				// Initially it is assumed they are all correct.
				$correctAnswer =  html_entity_decode($problem[0]['vastus']);
				$decision = "OK";
				$correctAnswer2 =  html_entity_decode($problem[0]['vastus2']);
				$decision2 = "OK";
				$correctAnswer3 =  html_entity_decode($problem[0]['vastus3']);
				$decision3 = "OK";
			
				//pikkuse kontroll
				if(mb_strlen($guess)!=mb_strlen($correctAnswer)){
					$decision = "Vale vastus";
				}
				if( mb_strlen($guess)!=mb_strlen($correctAnswer2)){
					$decision2 = "Vale vastus";
				}
				if ( mb_strlen($guess)!=mb_strlen($correctAnswer3)){
					$decision3 = "Vale vastus";
				}
				
				if( (mb_strlen($guess)!=mb_strlen($correctAnswer)) && (mb_strlen($guess)!=mb_strlen($correctAnswer2)) && (mb_strlen($guess)!=mb_strlen($correctAnswer3))){
					$feedback['decision'] = "Vale vastus";
					echo json_encode($feedback);
					break;
				}
				

				
				if((strcmp($correctAnswer,$guess)==0) || (strcmp($correctAnswer2,$guess)==0) || (strcmp($correctAnswer3,$guess)==0)){
					$feedback['decision'] = "OK";
					echo json_encode($feedback);
					$maxpoints = Problem::getMaxPoints($sql, $questionId);
					$setPoints = Solution::setPoints($sql, $maxpoints, $questionId);
					break;
				}
				
				//class for handling bound variables
				class variableMap
				{
					
				    // property declaration
				    public $occurrences = array();
				    public $quantor = "";
				    
				    /**
				     * 
				     * Constructor
				     * @param array $arg2 - array of occurences
				     * @param string $arg3- quantor 
				     */
					function __construct($arg2=array(), $arg3="") {
						  $this->occurrences = $arg2;
						  $this->quantor = $arg3;
					   }
				
				}
				//check if the guess if accurate but with different bound variables
				$j = mb_strlen($guess);
				
				$gVariables = array();
				$cVariables = array();
				$cVariables2 = array();
				$cVariables3 = array();
				
				
				//map bound variables in the first correct asnwer
				$j = mb_strlen($correctAnswer);
				if(mb_strlen($guess)==mb_strlen($correctAnswer)){
					for ($k = 0; $k < $j; $k++) {
						$char = mb_substr($correctAnswer, $k, 3);
						$matches = array();
						if($char === '∀' || $char === '∃'){
							//echo "Kvantor leitud ".$char."\n";
							if( $k < mb_strlen($correctAnswer) ){				
								//finding the occurences of a bound variable
								for($counter = $k+3;$counter<mb_strlen($correctAnswer);$counter++){
									if( $char === '∃'){
										//echo "E: ".mb_substr($correctAnswer, $counter, 1)."\n";
										//echo "str: ".mb_substr($correctAnswer, $k+3, 1)."\n";
									}
									if(mb_substr($correctAnswer, $counter, 1) === mb_substr($correctAnswer, $k+3, 1)){
										//echo "Klapp\n";
										$matches[] = $counter;
										}
									}
									//echo "Asukohad: ".mb_substr($correctAnswer, $k+3, 1)."\n";
									//print_r($matches);
									$cVariables[mb_substr($correctAnswer, $k+3, 1)]= new variableMap($matches, $char);
							}
							$k+=2;
						}
					}
				}
				
				//map bound variables in the second correct asnwer
				$j = mb_strlen($correctAnswer2);
				if(mb_strlen($guess)==mb_strlen($correctAnswer2)){
					for ($k = 0; $k < $j; $k++) {
						$char = mb_substr($correctAnswer2, $k, 3);
						$matches = array();
						if($char === '∀' || $char === '∃'){
							//echo "Kvantor leitud ".$char."\n";
							if( $k < mb_strlen($correctAnswer2) ){				
								//finding the occurences of a bound variable
								for($counter = $k+3;$counter<mb_strlen($correctAnswer2);$counter++){
									if( $char === '∃'){
										//echo "E: ".mb_substr($correctAnswer, $counter, 1)."\n";
										//echo "str: ".mb_substr($correctAnswer, $k+3, 1)."\n";
									}
									if(mb_substr($correctAnswer2, $counter, 1) === mb_substr($correctAnswer2, $k+3, 1)){
										//echo "Klapp\n";
										$matches[] = $counter;
										}
									}
									//echo "Asukohad: ".mb_substr($correctAnswer, $k+3, 1)."\n";
									//print_r($matches);
									$cVariables2[mb_substr($correctAnswer2, $k+3, 1)]= new variableMap($matches, $char);
							}
							$k+=2;
						}
					}
				}
				
				
				//map bound variables in the third correct asnwer
				$j = mb_strlen($correctAnswer3);
				if(mb_strlen($guess)==mb_strlen($correctAnswer3)){
					for ($k = 0; $k < $j; $k++) {
						$char = mb_substr($correctAnswer3, $k, 3);
						$matches = array();
						if($char === '∀' || $char === '∃'){
							//echo "Kvantor leitud ".$char."\n";
							if( $k < mb_strlen($correctAnswer) ){				
								//finding the occurences of a bound variable
								for($counter = $k+3;$counter<mb_strlen($correctAnswer3);$counter++){
									if( $char === '∃'){
										//echo "E: ".mb_substr($correctAnswer, $counter, 1)."\n";
										//echo "str: ".mb_substr($correctAnswer, $k+3, 1)."\n";
									}
									if(mb_substr($correctAnswer3, $counter, 1) === mb_substr($correctAnswer3, $k+3, 1)){
										//echo "Klapp\n";
										$matches[] = $counter;
										}
									}
									//echo "Asukohad: ".mb_substr($correctAnswer, $k+3, 1)."\n";
									//print_r($matches);
									$cVariables3[mb_substr($correctAnswer3, $k+3, 1)]= new variableMap($matches, $char);
							}
							$k+=2;
						}
					}
				}
				
				//map bound variables in  guess
				$j = mb_strlen($guess);
				//echo "oige pikkus ".$j;
				for ($k = 0; $k < $j; $k++) {
					$char = mb_substr($guess, $k, 3);
					$matches = array();
					if($char === '∀' || $char === '∃'){
						//echo "Kvantor leitud ".$char."\n";
						if( $k < mb_strlen($guess) ){				
							//finding the occurences of a bound variable
							for($counter = $k+3;$counter<mb_strlen($guess);$counter++){
								if( $char === '∃'){
									//echo "E: ".mb_substr($correctAnswer, $counter, 1)."\n";
									//echo "str: ".mb_substr($correctAnswer, $k+3, 1)."\n";
								}
								if(mb_substr($guess, $counter, 1) === mb_substr($guess, $k+3, 1)){
									//echo "Klapp\n";
									$matches[] = $counter;
									}
								}
								//echo "Asukohad: ".mb_substr($guess, $k+3, 1)."\n";
								//print_r($matches);
								$gVariables[mb_substr($guess, $k+3, 1)]= new variableMap($matches, $char);
						}
						$k+=2;
					}
				}
				
				
				// compare the students guess with the first correct answer
				if(mb_strlen($guess)==mb_strlen($correctAnswer)){
					for ($k = 0; $k < $j; $k++) {
						$charG = mb_substr($guess, $k, 1);
						$charC = mb_substr($correctAnswer, $k, 1);
						//echo $charG." charG-charC ".$charC."\n";
						if(strcmp($charG, $charC)==0){
						} else{
							$result = false;
							if(array_key_exists ($charG, $gVariables )){
								foreach($cVariables as $value){
									if(count(array_diff($gVariables[$charG]->occurrences, $value->occurrences))==0){
										if($gVariables[$charG]->quantor === $value->quantor){
											$result = true;
										}
									}
								}
							}
							if(!$result){
								$feedback['decision'] = "Vale vastus";
								echo json_encode($feedback);
								exit;
							}
						} 
					}
				}
				
				// compare the students guess with the second correct answer
				if(mb_strlen($guess)==mb_strlen($correctAnswer2)){
					for ($k = 0; $k < $j; $k++) {
						$charG = mb_substr($guess, $k, 1);
						$charC = mb_substr($correctAnswer2, $k, 1);
						//echo $charG." charG-charC ".$charC."\n";
						if(strcmp($charG, $charC)==0){
						} else{
							$result = false;
							if(array_key_exists ($charG, $gVariables )){
								foreach($cVariables2 as $value){
									if(count(array_diff($gVariables[$charG]->occurrences, $value->occurrences))==0){
										if($gVariables[$charG]->quantor === $value->quantor){
											$result = true;
										}
									}
								}
							}
							if(!$result){
								$feedback['decision'] = "Vale vastus";
								echo json_encode($feedback);
								exit;
							}
						} 
					}
				}
				
				// compare the students guess with the third correct answer
				if(mb_strlen($guess)==mb_strlen($correctAnswer3)){
					for ($k = 0; $k < $j; $k++) {
						$charG = mb_substr($guess, $k, 1);
						$charC = mb_substr($correctAnswer3, $k, 1);
						//echo $charG." charG-charC ".$charC."\n";
						if(strcmp($charG, $charC)==0){
						} else{
							$result = false;
							if(array_key_exists ($charG, $gVariables )){
								foreach($cVariables3 as $value){
									if(count(array_diff($gVariables[$charG]->occurrences, $value->occurrences))==0){
										if($gVariables[$charG]->quantor === $value->quantor){
											$result = true;
										}
									}
								}
							}
							if(!$result){
								$feedback['decision'] = "Vale vastus";
								echo json_encode($feedback);
								exit;
							}
						} 
					}
				}
				
				if((strcmp($decision,"OK")==0) || (strcmp($decision2,"OK")==0) || (strcmp($decision3,"OK")==0)){
					$feedback['decision'] = "OK";
					echo json_encode($feedback);
					//echo $decision." ".$decision2." ".mb_strlen($correctAnswer3);
					$maxpoints = Problem::getMaxPoints($sql, $questionId);
					$setPoints = Solution::setPoints($sql, $maxpoints, $questionId);
					break;
					
					
					
				} else {			
					$feedback['decision'] = "Vale vastus";
					echo json_encode($feedback);
					$zero = 0;
					$setPoints = Solution::setPoints($sql, $zero , $questionId);
					break;
					
				}
				
				
				//return data
				
				break;
				
				
			//create an answer and tie it to the solution
			case 'endResult':
				$result = $_POST['resultId'];
				$result = Result::endResult($sql, $result);
				break;
				
			//set feedback for an answer
			case 'setFeedback':
				$answerId = htmlentities($_POST['answerId']);
				$feedback = htmlentities($_POST['feedback']);
				$points = $_POST['points'];
				
				$result = Solution::setFeedback($sql, $feedback, $points, $answerId);
				if($result){
					echo "OK";	
				} else echo "Viga";
				
				break;
				
				
			//grade result
			case 'gradeResult':
				$resultId = $_POST['resultId'];
				$sum = Result::loadPoints($sql, $resultId);
				$sum = $sum[0]['summa'];
				$result = Result::gradeResult($sql, $resultId, $sum);
				if($result){
					echo "OK";	
				} else echo $result;
				
				break;
				
				
		}
}



	
?>
